package com.newhopegroup.webcommons.sms;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.common.io.CharStreams;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by liusen on 15-7-10.
 */
public class ShortMessageService {

    private static final Logger logger = LoggerFactory.getLogger(ShortMessageService.class);
    private static final CloseableHttpClient httpclient = HttpClients.createDefault();
    private static final ObjectMapper mapper = new ObjectMapper();
    private static final String SIGN = "【新希望保理】";

    public static final Map<String, String> errCode = new HashMap<String, String>() {
        {
            put("1", "操作成功");
            put("-1", "发送时间不在允许范围内");
            put("-2", "含有非法字符");
            put("-3", "合法号码数是0");
            put("-4", "费用不足");
            put("-5", "不允许修改");
            put("-6", "账号密码不匹配");
        }
    };
//            ImmutableMap.of("1", "操作成功",
//            "-1", "发送时间不在允许范围内",
//            "-2", "含有非法字符",
//            "-3", "合法号码数是0");


    public static void sendMessage(String mobileNumber, String message) throws ShortMessageServiceException {
        URI uri = null;
        try {
            uri = new URIBuilder()
                    .setScheme("http")
                    .setHost("www.cloudsms.cc")
                    .setPath("/send")
                    .setParameter("account", "newhope")
                    .setParameter("pwd", "newhope")
                    .setParameter("mobiles", mobileNumber)
                    .setParameter("content", SIGN + message)
                    .build();
            logger.info("URI=[{}]", uri.toString());

        } catch (URISyntaxException e) {
            logger.error(e.getMessage(), e);
            throw new ShortMessageServiceException(e);
        }

        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(5000)
                .setConnectTimeout(5000)
                .build();

        HttpPost httpPost = new HttpPost(uri);
        httpPost.setConfig(requestConfig);

        CloseableHttpResponse response1 = null;
        try {
            response1 = httpclient.execute(httpPost);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new ShortMessageServiceException(e);
        }
        String context = "";
        try {
            HttpEntity entity = response1.getEntity();
            if (entity != null) {
                context = CharStreams.toString(new InputStreamReader(entity.getContent(), Charsets.UTF_8));
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new ShortMessageServiceException(e);
        } finally {
            try {
                response1.close();
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
                throw new ShortMessageServiceException(e);
            }
        }
        logger.info("response context [{}]", context);

        Map<String, String> map = null;
        try {
            map = mapper.readValue(context, new TypeReference<HashMap<String, String>>() {
            });
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new ShortMessageServiceException(e);
        }
        String returnCode = Optional.of(map.get("result")).get();
        logger.debug("returnCode [{}]", returnCode);
        if (!StringUtils.equals(returnCode, "1")) {
            String returnMessage = Optional.of(errCode.get(returnCode)).get();
            throw new ShortMessageServiceException(returnMessage);
        }

    }

}
